//login.js
var jsencrypt = require('../../vendor/jsencrypt.min');
var enc = require('../../vendor/enc');

Page({
  data: {
    logs: []
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(function (log) {
        //return util.formatTime(new Date(log))
      })
    })
  },
  formSubmit: function (e) {
    var encryptor = new jsencrypt.Encryptor();
    var base64_lib = new enc.Base64();

    encryptor.setPublicKey(getApp().cnbConfig.publicKey);

    var username = encryptor.encrypt(e.detail.value.username);
    var password = encryptor.encrypt(e.detail.value.password);

    var auth = base64_lib.encode(getApp().cnbConfig.clientId + ":" + getApp().cnbConfig.clientSecret);

    wx.request({
     url: getApp().cnbConfig.apiPrefix + '/token',
     method: 'POST',
     dataType: "json",
     data: {username: username, password: password, grant_type: "password"},
     header: {
        "Content-Type":"application/x-www-form-urlencoded",
        "Authorization":"Basic " + auth,
     },
     success: function(res){
       console.log(res);

       if (res.data.error) {
         wx.showToast({title: "授权失败 标识：" + res.data.error});
         return false;
       }
       
       wx.setStorageSync('user-oauth', res.data);
       getApp().accessToken = res.data.access_token;
       //得到用户详细信息
       wx.request({
          url: getApp().cnbConfig.apiPrefix + '/api/Users',
          method: 'GET',
          dataType: "json",
          data: {},
          header: {
              "Authorization":"Bearer " + getApp().accessToken,
          },
          success: function(res){
            console.log(res);

            if (res.data.error) {
              wx.showToast({title: "请求用户数据失败 标识：" + res.data.error});
              return false;
            }
            
            wx.setStorageSync('user', res.data);            
            getApp().user = res.data
            wx.switchTab({url: "/pages/index/index"});
          },
          fail: function(e) {
              
          },
          complete: function() {
            // complete
          }
        })

       getApp().user = res.data
     },
     fail: function(e) {
        
     },
     complete: function() {
       // complete
     }
   })
  }
})
